package com.example.front.main.user;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.front.MyApplication;
import com.example.front.R;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class UserInformationActivity extends AppCompatActivity {
    private TextView username_textView;
    private TextView sex_textView;
    private TextView phone_textView;
    private TextView email_textView;
    private ImageView userImage;
    private String URL;
    private MyApplication myApplication;

    // 拍照和相册的requestCode
    private static final int CAMERA_REQUEST_CODE = 0x00000010;
    public static final int CHOOSE_PHOTO = 0x00000011;

    /**
     * 用于保存拍照图片的uri
     */
    private Uri mCameraUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_information);

        username_textView = findViewById(R.id.username_textView);
        sex_textView = findViewById(R.id.sex_textView);
        phone_textView = findViewById(R.id.phone_textView);
        email_textView = findViewById(R.id.email_textView);
        userImage = findViewById(R.id.user_image);

        myApplication = (MyApplication) getApplication();
        URL = myApplication.getURL();

        SharedPreferences sharedPreferences = getSharedPreferences("Login", Context.MODE_PRIVATE);
        String userHead = sharedPreferences.getString("photo", "");
        String username = sharedPreferences.getString("username", "");
        String phone = sharedPreferences.getString("phone", "");
        String email = sharedPreferences.getString("email", "未设置");

        if (userHead.equals("null"))
            userHead = "";
        Glide.with(UserInformationActivity.this)
                .load(userHead)
                .error(R.drawable.head)
                .crossFade()
                .into(userImage);
        username_textView.setText(username);
        phone_textView.setText(phone);
        if(email.equals("") || email.equals("null"))
            email_textView.setText("未设置");
        else email_textView.setText(email);
        if (sharedPreferences.getInt("sex", 0) == 1)
            sex_textView.setText("男");
        else sex_textView.setText("女");
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        SharedPreferences sharedPreferences = getSharedPreferences("Login", Context.MODE_PRIVATE);
        String userHead = sharedPreferences.getString("photo", "");
        String username = sharedPreferences.getString("username", "");
        String phone = sharedPreferences.getString("phone", "");
        String email = sharedPreferences.getString("email", "未设置");

        if (userHead.equals("null"))
            userHead = "";
        Glide.with(UserInformationActivity.this)
                .load(userHead)
                .error(R.drawable.head)
                .crossFade()
                .into(userImage);
        username_textView.setText(username);
        phone_textView.setText(phone);
        if(email.equals("") || email.equals("null"))
            email_textView.setText("未设置");
        else email_textView.setText(email);
        if (sharedPreferences.getInt("sex", 0) == 1) sex_textView.setText("男");
        else sex_textView.setText("女");
    }

    public void username_onClick(View view) {
        Intent intent = new Intent(UserInformationActivity.this, UserNameModify.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void sex_onClick(View view) {
        Intent intent = new Intent(UserInformationActivity.this, SexModify.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void phone_onClick(View view) {
        Intent intent = new Intent(UserInformationActivity.this, PhoneModify.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void email_onClick(View view) {
        Intent intent = new Intent(UserInformationActivity.this, EmailModify.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void password_onClick(View view) {
        Intent intent = new Intent(UserInformationActivity.this, PasswordModify.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void showPopueWindow(View view) {
        View popView = View.inflate(this, R.layout.popupwindow_camera_need, null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels * 1 / 3;

        final PopupWindow popupWindow = new PopupWindow(popView, weight, height);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(UserInformationActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(UserInformationActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                }else {
                    Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent,CHOOSE_PHOTO); //打开相册
                    popupWindow.dismiss();
                }
            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(UserInformationActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(UserInformationActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                }else {
                    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (captureIntent.resolveActivity(getPackageManager()) != null) {
                        Uri photoUri = null;
                        photoUri = createImageUri();

                        mCameraUri = photoUri;
                        if (photoUri != null) {
                            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                            captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                            startActivityForResult(captureIntent, CAMERA_REQUEST_CODE); //打开相机
                            popupWindow.dismiss();
                        }
                    }
                }
            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case CAMERA_REQUEST_CODE: {
                if (RESULT_OK == resultCode) {
                        File file = getFileByUri(mCameraUri);
                        SharedPreferences sharedPreferences = getSharedPreferences("Login", Context.MODE_PRIVATE);
                        String account = sharedPreferences.getString("account", "");
                        String fileName = String.valueOf(System.currentTimeMillis());
                        Toast.makeText(UserInformationActivity.this, "正在上传头像，请稍等", Toast.LENGTH_LONG).show();
                        OkHttpUtils.post()
                                .url("https://cloud.662359.cn/api.php")
                                .addFile("file", fileName + ".png", file)
                                .addParams("show", "0")
                                .addParams("ispwd", "0")
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Request request, Exception e) {
                                        Toast.makeText(UserInformationActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            if (jsonObject.getInt("code") == 0) {
                                                OkHttpUtils.post()
                                                        .url(URL + "/user/mphoto")
                                                        .addParams("account", account)
                                                        .addParams("photo", jsonObject.getString("viewurl"))
                                                        .build()
                                                        .execute(new StringCallback() {
                                                            @Override
                                                            public void onError(Request request, Exception e) {
                                                                Toast.makeText(UserInformationActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                                                            }

                                                            @Override
                                                            public void onResponse(String response) {
                                                                try {
                                                                    Glide.with(UserInformationActivity.this)
                                                                            .load(jsonObject.getString("viewurl"))
                                                                            .error(R.drawable.error)
                                                                            .crossFade()
                                                                            .into(userImage);
                                                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                                                    editor.putString("photo", jsonObject.getString("viewurl"));
                                                                    editor.apply();
                                                                } catch (JSONException e) {
                                                                    e.printStackTrace();
                                                                }
                                                                Toast.makeText(UserInformationActivity.this, "头像更新成功", Toast.LENGTH_SHORT).show();
                                                            }
                                                        });
                                            } else {
                                                Toast.makeText(UserInformationActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });

                }
                break;
            }
            case CHOOSE_PHOTO: {
                if (RESULT_OK == resultCode) {
                    Uri selectedImage = data.getData();

                    //从哪个内容提供者查询，这里是相册
                    String[] filePathCols = {MediaStore.Images.Media.DATA};
                    //从内容提供者中查询到数据       getContentResolver获得内容提供者，投影查询，结果集中只有对应的路径
                    Cursor c = UserInformationActivity.this.getContentResolver().query(selectedImage, filePathCols,
                            null, null, null);
                    //头结点不存数据
                    c.moveToFirst();
                    //查询内容提供者（相册），在结果集中所对应的列ID
                    int colIdx = c.getColumnIndex(filePathCols[0]);
                    //根据列ID取到对应的结果（真实路径）
                    String picPath = c.getString(colIdx);
                    //加载文件，为了获得文件名
                    File file = new File(picPath);
                    SharedPreferences sharedPreferences = getSharedPreferences("Login", Context.MODE_PRIVATE);
                    String account = sharedPreferences.getString("account", "");
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Toast.makeText(UserInformationActivity.this, "正在上传头像，请稍等", Toast.LENGTH_LONG).show();
                    OkHttpUtils.post()
                            .url("https://cloud.662359.cn/api.php")
                            .addFile("file", fileName + ".png", file)
                            .addParams("show", "0")
                            .addParams("ispwd", "0")
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    Toast.makeText(UserInformationActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        if (jsonObject.getInt("code") == 0) {
                                            OkHttpUtils.post()
                                                    .url(URL + "/user/mphoto")
                                                    .addParams("account", account)
                                                    .addParams("photo", jsonObject.getString("viewurl"))
                                                    .build()
                                                    .execute(new StringCallback() {
                                                        @Override
                                                        public void onError(Request request, Exception e) {
                                                            Toast.makeText(UserInformationActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                                                        }

                                                        @Override
                                                        public void onResponse(String response) {
                                                            try {
                                                                Glide.with(UserInformationActivity.this)
                                                                        .load(jsonObject.getString("viewurl"))
                                                                        .error(R.drawable.error)
                                                                        .crossFade()
                                                                        .into(userImage);
                                                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                                                editor.putString("photo", jsonObject.getString("viewurl"));
                                                                editor.apply();
                                                            } catch (JSONException e) {
                                                                e.printStackTrace();
                                                            }
                                                            Toast.makeText(UserInformationActivity.this, "头像更新成功", Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                        } else {
                                            Toast.makeText(UserInformationActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                    break;
                }
                break;
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     *
     * @return 图片的uri
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    /**
     * 通过Uri返回File文件
     * 注意：通过相机的是类似content://media/external/images/media/97596
     * 通过相册选择的：file:///storage/sdcard0/DCIM/Camera/IMG_20150423_161955.jpg
     * 通过查询获取实际的地址
     *
     * @param uri
     * @return
     */
    public File getFileByUri(Uri uri) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = this.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(path);
        } else {
        }
        return null;
    }
}
